goog.provide('form');

goog.require('datastore');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.ui.ComboBox');
goog.require('goog.ui.ComboBoxItem');
goog.require('goog.ui.Dialog');
goog.require('goog.ui.Dialog.ButtonSet');
goog.require('page');


/**
 * The name for this test to be used when displaying results.
 *
 * @type {string}
 * @const
 */
form.testName = 'meta data';


/**
 * Indicates that the form is completed.
 *
 * @type {boolean}
 */
form.done = false;


/**
 * Dialoge box for holding questions.
 *
 * @type {goog.ui.Dialog}
 */
form.dialog = new goog.ui.Dialog(null, true);


/**
 * Dialoge box for holding documentation.
 *
 * @type {goog.ui.Dialog}
 */
form.info = new goog.ui.Dialog(null, true);


/**
 * Group of questions to display.
 *
 * @type {Object.<string, goog.ui.{*}>}
 */
form.questions = {'connection': new goog.ui.ComboBox(),
  'location': new goog.ui.ComboBox()};


/**
 * A list of connection types.
 *
 * @type {Array.<string>}
 */
form.connectionItems = ['Wired LAN',
  'Wired Cable',
  'Wired DSL',
  'Wired Unknown',
  'Wifi LAN',
  'Wifi Cable',
  'Wifi DSL',
  'Wifi Unknown',
  'Mobile 3G',
  'Mobile 4G',
  'Dial-up'];


/**
 * A list of common types of locations.
 *
 * @type {Array.<string>}
 */
form.locationItems = ['Home',
  'Work',
  'School',
  'Library',
  'Public Wifi',
  'Hotel',
  'Internet Cafe',
  'Other'];


/**
 * A method to capitalize the first letter of a string.
 *
 * @param {string} s the string to capitalize.
 *
 * @return {string} The modified string.
 */
function capitaliseFirstLetter(s)
{
  return s[0].toUpperCase() + s.slice(1);
}


/**
 * Do the setup work for the select items.
 */
form.selectSetups = function() {
  //connection type
  form.questions['connection'].setUseDropdownArrow(true);
  form.questions['connection'].setDefaultText(nsi18n('formConnection'));
  for (c in form.connectionItems) {
    form.questions['connection'].addItem(
        new goog.ui.ComboBoxItem(form.connectionItems[c]));
  }

  //ISP
  form.questions['location'].setUseDropdownArrow(true);
  form.questions['location'].setDefaultText(nsi18n('formLocation'));
  for (i in form.locationItems) {
    form.questions['location'].addItem(
        new goog.ui.ComboBoxItem(form.locationItems[i]));
  }
};


/**
 * The setup method for displaying a form popup.
 */
form.start = function() {
  page.welcomeSetup();
  form.infoSetup();
  goog.events.listen(page.goButton, goog.ui.Component.EventType.ACTION,
      form.show);
  form.selectSetups();
  form.dialog.setTitle(nsi18n('formSettingsTitle'));
  form.buttonSet = goog.ui.Dialog.ButtonSet.createOkCancel();
  form.dialog.setButtonSet(form.buttonSet);
  var frameContent = form.dialog.getContentElement();
  var questionsCol = goog.dom.createDom('td',
      {'valign': 'top'});
  var tr = goog.dom.createDom('tr', null, questionsCol);
  var table = goog.dom.createDom('table', null, tr);
  goog.dom.appendChild(frameContent, table);

  var req = goog.dom.createDom('span',
      {'style': 'font: normal small arial, sans-serif; color: #aa0000;'}, ' *');
  var inst = goog.dom.createDom('div', {'style': 'font-style:italic;'}, req,
      nsi18n('formReqField'));
  goog.dom.appendChild(questionsCol, inst);
  for (q in form.questions) {
    var tmp = goog.dom.createDom('div');
    form.questions[q].render(tmp);
    goog.dom.appendChild(questionsCol, tmp);
    if (q == 'connection') {
      req = goog.dom.createDom('span',
          {'style': 'font: normal small arial, sans-serif; color: #aa0000;'},
          ' *');
      goog.dom.appendChild(tmp, req);
    }
  }

  //Disable OK button
  form.buttonSet.setButtonEnabled(goog.ui.Dialog.DefaultButtonKeys.OK, false);
};


/**
 * The setup method for displaying a documentation popup.
 */
form.infoSetup = function() {
  goog.events.listen(page.infoButton, goog.ui.Component.EventType.ACTION,
      form.showInfo);
  form.info.setTitle(nsi18n('formInfoTitle'));
  form.infoButtonSet = goog.ui.Dialog.ButtonSet.createOk();
  form.info.setButtonSet(form.infoButtonSet);
  var frameContent = form.info.getContentElement();
  var info1Div = goog.dom.createDom('div', {'class': 'message'},
      nsi18n('formInfo1'));
  goog.dom.appendChild(frameContent, info1Div);
  var info2Div = goog.dom.createDom('div', {'class': 'message'},
      nsi18n('formInfo2'));
  goog.dom.appendChild(frameContent, info2Div);
  var info3Div = goog.dom.createDom('div', {'class': 'message'},
      nsi18n('formInfo3'));
  goog.dom.appendChild(frameContent, info3Div);
  var newsLink = goog.dom.createDom('a', {'href': 'http://news.net-score.org',
    'target': '_blank'}, 'news.net-score.org');
  var info4Div = goog.dom.createDom('div', {'class': 'message'},
      nsi18n('formInfo4'), newsLink, '.');
  goog.dom.appendChild(frameContent, info4Div);
};


/**
 * Enables the buttons on the form.
 *
 * @param {goog.ui.Component.EventType} e the CHANGE event.
 */
form.testEnable = function(e) {
  if (form.questions['connection'].getValue() != '') {
    form.buttonSet.setButtonEnabled(goog.ui.Dialog.DefaultButtonKeys.OK, true);
  }
};
//Register this function call with the connection type input
goog.events.listen(form.questions['connection'],
    goog.ui.Component.EventType.CHANGE, form.testEnable);


/**
 * Processes info on the form.
 *
 * @param {goog.ui.Dialog.EventType} e the SELECT event.
 */
form.process = function(e) {
  if (e.key == 'cancel') {
    page.welcomeSetup();
  }
  else {
    //let the server know the test is starting
    datastore.updateRequestTime();
    page.progressSetup();
    for (q in form.questions) {
      datastore.json['form' + capitaliseFirstLetter(q)] =
          form.questions[q].getValue();
    }

    //This is a safe place to git rid of elements we no longer need.
    form.dialog.dispose();
    form.info.dispose();
    page.goButton.dispose();
    page.infoButton.dispose();

    if (form.nextFunction) {
      form.nextFunction();
    }
  }
  form.done = true;
};
//Register this function call with the form buttons
goog.events.listen(form.dialog, goog.ui.Dialog.EventType.SELECT, form.process);


/**
 * Hides the documentation popup.
 *
 * @param {goog.ui.Dialog.EventType} e the SELECT event.
 */
form.hideInfo = function(e) {
  page.welcomeSetup();
};
//Register this function call with the popup
goog.events.listen(form.info, goog.ui.Dialog.EventType.SELECT, form.hideInfo);


/**
 * Show the documentation popup.
 */
form.showInfo = function() {
  page.welcomeHide();
  form.info.setVisible(true);
};


/**
 * Show the form popup.
 */
form.show = function() {
  page.welcomeHide();
  form.dialog.setVisible(true);
};


/**
 * Displays the info collected by the form.
 */
form.results = function() {
  var resultLink = goog.dom.createDom('a', {'href': page.resultDetailUrl +
        datastore.resultKey}, nsi18n('formResultLink'));
  var otherDescripDiv;
  if (datastore.resultKey) {
    otherDescripDiv = goog.dom.createDom('div', {'class': 'message'},
        nsi18n('formOtherDescrip'), nsi18n('formLinkDescrip'), resultLink);
  }
  else {
    otherDescripDiv = goog.dom.createDom('div', {'class': 'message'},
        otherDescrip);
  }
  var otherTableDisplayDiv = goog.dom.createDom('div', {'class': 'table'});
  var contentDiv = goog.dom.createDom('div', {},
                                      otherDescripDiv, otherTableDisplayDiv);
  page.resultsAppend(form.testName, contentDiv);

  var otherLables = [];
  var otherValues = [];
  var i = 0;
  for (q in form.questions) {
    var key = 'form' + capitaliseFirstLetter(q);
    if (datastore.json[key] != undefined && datastore.json[key] != '') {
      otherLables[i] = q;
      otherValues[i] = datastore.json[key];
      i++;
    }
  }

  var otherDataObj = results.dataToObj(otherLables, otherValues,
      nsi18n('Field'), nsi18n('Value'), 'string', 'number');
  results.table(otherDataObj, otherTableDisplayDiv);
};
